import { ScrollView, Text, View } from "@tarojs/components";
import { useCreation } from "ahooks";
import Taro from "@tarojs/taro";


import ByTag from "@/components/ui/ByTag";
import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import ByIcon from "@/components/ui/ByIcon";
import Card from "@/components/common/Card";
import ByText from "@/components/ui/ByText";
import Moment from "@/components/app/Moment";
import ByEmpty from "@/components/ui/ByEmpty";
import BySpace from "@/components/ui/BySpace";
import ByButton from "@/components/ui/ByButton";
import UserItem from "@/components/app/UserItem";

import ByPopupBottom from "@/components/ui/ByPopupBottom";
import { SkeletonGroup } from "@/components/app/Skeleton";

import ApiCrm from "@/api/crm";
import ApiWork from "@/api/work";
import useFetch from "@/hooks/useFetch";
import useGetHolidayList from "@/hooks/useGetHolidayList";

import type { ByPopupBottomEvent } from "@/components/ui/ByPopupBottom";
import { ContractInfo } from "@/types/contract";
import {
  getDaysBetweenDate,
  getPeriodEndDate,
  objectToQueryString,
} from "@/utils";


const tagMap = {
  0: { color: "info", label: "未开工" },
  1: { color: "primary", label: "已开工" },
  2: { color: "success", label: "已完工" },
} as const;

const PlanItem = ({ source, intentCustomerId, onCancel }: any) => {
  const { startState, completeState, workerList, constructionPlanId } = source;
  const tag = tagMap[completeState === 88 ? 2 : startState === 1 ? 1 : 0];

  // 跳转路由
  const handleNavigateTo = () => {
    const ids = workerList?.map((e) => e.workerDistributeId) || [];
    const query = objectToQueryString({
      workerids: ids,
      intentCustomerId,
      constructionPlanId,
    });

    Taro.navigateTo({
      url: `/packageWork/pages/plan/execute?${query}`,
    }).then(onCancel);
  };

  return (
    <Card className="mb-2" onClick={handleNavigateTo}>
      <ByRow align="center">
        <ByTag variant="filled" rounded={false} size="small" type={tag.color}>
          {tag.label}
        </ByTag>

        <ByCol span="auto" className="px-2">
          {source.constructionProjectName}
          {source.isMustComplete && <Text>（必做）</Text>}
        </ByCol>

        <Text className="text-second">
          <Moment value={source.planStartDate} type="month" />
          <Text>~</Text>
          <Moment value={source.planFinishDate} type="month" />
        </Text>
      </ByRow>

      {source.extensionDate > 0 && (
        <View className="my-2 text-right text-sm">
          <ByText type="error">延期{source.extensionDate}天</ByText>
        </View>
      )}

      <ByRow align="center" className="mt-3">
        <ByCol span="auto">
          <BySpace>
            {source.workerList?.map((worker) => (
              <UserItem size={50} name={worker.workerName} />
            ))}
          </BySpace>
        </ByCol>

        <ByIcon name="ArrowRight" className="text-primary" size={24} />
      </ByRow>
    </Card>
  );
};

export default ({
  intentCustomerId,
  onCancel,
}: { intentCustomerId: number } & ByPopupBottomEvent) => {
  // 假期列表
  const [holidays] = useGetHolidayList();

  // 获取合同信息
  const { data: contractInfo, error } = useFetch<ContractInfo>(
    ApiWork.getContractInfo,
    {
      showErrorToast: false,
      defaultParams: [{ intentCustomerId }],
      onAfter: (res: any) => res.contractInfo,
    }
  );

  // 获取施工列表
  const { data, loading, refresh } = useFetch<any>(ApiCrm.getConstructionPlanList, {
    defaultParams: [{ intentCustomerId }],
  });

  // 必做项目是否已完工
  const hadCompleted = !data?.list
    .filter((e) => e.isMustComplete)
    .every((e) => e.completeState !== 88);

  // 获取上一个必做项
  const findLastSource = (targetIndex: number) => {
    const target = data.list[targetIndex];

    // 当前施工项非必须 || 索引==0时，没有前置项目
    if (!target.isMustComplete || targetIndex == 0) return undefined;

    return (data!.list as any[])
      .slice(0, targetIndex)
      .reverse()
      .find((e) => e.isMustComplete);
  };

  const dateView = useCreation(() => {
    // 只有单存在realBeginDate时，才需要计算合同时间
    if (contractInfo && data && holidays) {
      const {
        realBeginDate,
        isSkipHoliday,
        contractDuration = 0,
      } = contractInfo;

      // 合同结束时间
      const contractEndDate = realBeginDate
        ? getPeriodEndDate(
          realBeginDate,
          contractDuration,
          holidays,
          isSkipHoliday ?? data.isSkipHoliday
        )
        : "";

      const isStarted = !!data?.realStartDate;

      // 施工开始时间
      const startDate = isStarted ? data.realStartDate : data.planStartDate;
      // 施工结束时间
      const endDate = isStarted ? data.realEndDate : data.planFinishDate;
      // 施工周期（不用管是否节假日施工）
      const duration = getDaysBetweenDate(startDate, endDate);

      return {
        // 合同工期
        contractEndDate,
        contractBeginDate: realBeginDate,
        contractDuration,

        // 施工工期
        startDate,
        endDate,
        duration,
      };
    }
  }, [contractInfo, data, holidays]);

  const { loading: submitLoading, run: submit } = useFetch(
    ApiWork.submitConstruction,
    "POST",
    {
      manual: true,
      onSuccess() {
        Taro.showToast({ title: "提交成功" })
        refresh()
      }
    }
  );

  const handleSubmit = async () => {
    const { confirm } = await Taro.showModal({
      title: "提示",
      content: "是否确认提交？",
    });

    if (confirm) {
      submit({
        intentCustomerId,
        constructionId: data.constructionId,
      });
    }
  };

  return (
    <ByPopupBottom title="计划执行" onCancel={onCancel}>
      {
        <>
          <ByRow className="p-3 text-sm" content="between">
            <View>
              <ByText type="third" size="xs">
                合同工期:
              </ByText>
              <Moment value={dateView?.contractBeginDate} type="month" />
              <Text>~</Text>
              <Moment value={dateView?.contractEndDate} type="month" />
            </View>

            <View>
              <ByText type="third" size="xs">
                施工工期:
              </ByText>
              <Moment value={dateView?.startDate} type="month" />
              <Text>~</Text>
              <Moment value={dateView?.endDate} type="month" />
            </View>

            {data && (
              <ByText size="xs">
                节假日{data.isSkipHoliday ? "不" : ""}施工
              </ByText>
            )}
          </ByRow>

          <ScrollView scrollY={true} className="h-[65vh]">
            <View className="py-3 px-4">
              {loading && data?.list.length < 1 && <SkeletonGroup />}

              {data?.list.map((item, index) => (
                <PlanItem
                  source={item}
                  key={item.constructionPlanId}
                  intentCustomerId={intentCustomerId}
                  lastSource={findLastSource(index)}
                  onCancel={onCancel}
                />
              ))}
            </View>

            {error && <ByEmpty text="未查询到数据记录" />}

            {hadCompleted && !data?.isSubmit && (
              <View className="pb-2">
                <ByButton
                  round
                  size="large"
                  className="w-2/3"
                  loading={submitLoading}
                  onClick={handleSubmit}
                >
                  提交确认
                </ByButton>
              </View>
            )}
          </ScrollView>
        </>
      }
    </ByPopupBottom>
  );
};
